package com.example;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.example.entity.User;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Map;

/**
 * BeanUtil：JavaBean 与 Map/对象之间的桥梁
 * 功能	            方法
 * Bean → Map	    beanToMap()
 * Map → Bean	    mapToBean()
 * 属性拷贝	        copyProperties()
 * 判断字段为空	    hasNullField()
 */
@SpringBootTest
public class LearnBeanUtil {

    /**
     * Bean ↔ Map 转换、字段提取、属性复制
     */

    @Test
    public void test1() {
        // Bean → Map
        User user = new User("Alice", 23);
        Map<String, Object> map = BeanUtil.beanToMap(user);
        System.out.println(map);
    }

    @Test
    public void test2() {
        // Map → Bean
        Map<Object, Object> build = MapUtil.builder()
                .put("name", "Alice")
                .put("age", 23)
                .build();
        User user = BeanUtil.mapToBean(build, User.class, true);
        System.out.println(user);
    }

    @Test
    public void test3() {
        // 属性拷贝
        User u1 = new User("A", 18);
        User u2 = new User();
        BeanUtil.copyProperties(u1, u2);
        System.out.println(u1);
        System.out.println(u2);
    }

    @Test
    public void test4() {
        // json
        String json = "{\"name\":\"Sam\",\"age\":29}";
        System.out.println(json);
        // map
        Map<String, Object> map = JSONUtil.toBean(json, Map.class);
        System.out.println(map);
        // bean
        User user = BeanUtil.mapToBean(map, User.class, true);
        System.out.println(user);
    }

}
